package 串;

public class BruteForce {
	
	public static void main(String[] args) {
		System.out.println(bruteForce1("Hello World", "H") == 0);
		System.out.println(bruteForce1("Hello World", "or") == 7);
		System.out.println(bruteForce1("Hello World", "d") == 10);
	}
	
	/**
	 * 实现一
	 */
	public static int bruteForce(String text, String pattern) {
		if (text == null || pattern == null) return -1;
		int tlen = text.length(), plen = pattern.length();
		if (tlen == 0 || plen == 0 || plen > tlen) return -1;
		
		char[] tChars = text.toCharArray();
		char[] pChars = pattern.toCharArray();
		int ti = 0, pi = 0;
		int tiMax = tlen - plen;
		while (pi < plen && ti - pi <= tiMax) {
			if (tChars[ti] == pChars[pi]) {
				ti++;
				pi++;
			} else {
				ti -= pi - 1;
				pi = 0;
			}
		}
		return pi == plen ? ti - pi : -1;
	}
	
	/**
	 * 实现二
	 */
	public static int bruteForce1(String text, String pattern) {
		if (text == null || pattern == null) return -1;
		int tlen = text.length(), plen = pattern.length();
		if (tlen == 0 || plen == 0 || plen > tlen) return -1;
		
		char[] tChars = text.toCharArray();
		char[] pChars = pattern.toCharArray();
		int tiMax = tlen - plen;
		for (int ti = 0; ti <= tiMax; ti++) {
			int pi = 0;
			for (; pi < plen; pi++) {
				if (tChars[ti + pi] != pChars[pi]) break;
			}
			if (pi == plen) return ti;
		}
		return -1;
	}
}
